<?php
/**
 * Date: 2017/4/16
 * Time: 21:55
 */

namespace Tools;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;


class Rabbitmq
{
    private $logger;

    private $config;

    private $connection;

    private $channel;

    public function __construct($logger, $config)
    {
        $this->logger = $logger;
        $this->config = $config;

        $this->connection = new AMQPStreamConnection($config['server'], $config['port'], $config['username'], $config['password'], $config['vhost']);
        $this->channel = $this->connection->channel();
        $this->channel->queue_declare($config['queue_name'], false, true, false, false);
        $this->channel->exchange_declare($config['exchange'], $config['exchange_type'], false, true, false);
        $this->channel->queue_bind($config['queue_name'], $config['exchange']);
    }

    public function dump_config()
    {
        $this->logger->info($this->config);
    }

    public function sendMsg($msg){

    }

    public function start_consume(){
        $this->channel->basic_consume($this->config['queue_name'], $this->config['consumer_tag'], false, false, false, false, 'process_message');
        //register_shutdown_function('shutdown', $this->channel, $this->connection);
        while (count($this->channel->callbacks)) {
            $this->channel->wait();
        }
    }

    function process_message($message)
    {
        $this->logger->info("\n--------\n");
        $this->logger->info($message->body);
        $this->logger->info("\n--------\n");

        $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);

        // Send a message with the string "quit" to cancel the consumer.
        if ($message->body === 'quit') {
            $message->delivery_info['channel']->basic_cancel($message->delivery_info['consumer_tag']);
        }
    }

    function shutdown($channel, $connection)
    {
        $channel->close();
        $connection->close();
    }

}

